import re
from rest_framework import serializers
from users.models import User
from django_redis import get_redis_connection


class UserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(max_length=20,min_length=8,write_only=True)
    sms_code = serializers.CharField(max_length=6,min_length=6,write_only=True)
    allow = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = ("id","username","mobile","password","password2","sms_code","allow")
        extra_kwargs = {
            "username":{
                "max_length":20,
                "min_length":5,
                "error_messages":{
                    "max_length":"名字太长",
                    "min_length":"名字太短"
                }
            },
            "password":{
                "write_only":True,
                "max_length":20,
                "min_length":8,
                "error_messages":{
                    "max_length":"密码过长",
                    "min_length":"密码过短"
                }
            }
        }


        def validate_mobile(self,value):
            print(value)
            if not re.match(r"^1[3-9]\d{9}$",value):
                return serializers.ValidationError("手机号不正确")
            return value


        def validate_allow(self,value):
            if value != "true":
                return serializers.ValidationError("状态未选中")

            return value

        def validate(self,attrs):
            if attrs["password"] != attrs["password2"]:
                return serializers.ValidationError("两次输入的密码不一致")


            conn = get_redis_connection("verifications")
            sms_code_real = conn.get("sms_code_%s"%attrs["mobile"])
            if not sms_code_real:
                return serializers.ValidationError("短信失效")

            if attrs["sms_code"] != sms_code_real.decode():
                return  serializers.ValidationError("短信不一致")

            return attrs


        def cteate(self,validated_data):
            print(validated_data)
            del validated_data["password2"]
            del validated_data["sms_code"]
            del validated_data["allow"]
            user = super().create(validated_data)
            user.set_password(validated_data["password"])
            user.save()
            return user






